package com.studerb.view.newsGroups;

import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.studerb.events.TaskEvent;
import com.studerb.events.listener.AbstractTaskListener;
import com.studerb.service.interfaces.INewsGroupService;

public class NewsGroupsPane extends JPanel implements ActionListener {
    @Autowired protected INewsGroupService newsGroupService;
    @Autowired protected NewsGroupsTable newsGroupsTable;
    @Autowired protected NewsGroupDetailsPane newsGroupDetailsPanel;
    
    private JButton updateButton;
    private JSplitPane splitPane;
    private JScrollPane leftPanel;
    private JScrollPane rightPanel;
    
    private JPanel buttonPanel;

    @Override public void actionPerformed(ActionEvent e) {
        if (e.getSource() == updateButton){
            try{
                newsGroupService.downloadAllNewsGroups(new newsGroupsTaskListener());
                newsGroupsTable.setEnabled(false);
                updateButton.setEnabled(false);
                setCursor(new Cursor(Cursor.WAIT_CURSOR));
            }
            catch(Exception exception){
                JOptionPane.showMessageDialog(this, ExceptionUtils.getRootCauseMessage(exception));
            }
        }
    }

    public void init() {
        this.setLayout(new BorderLayout());

        leftPanel = new JScrollPane();
        leftPanel.setViewportView(newsGroupsTable);
        rightPanel = new JScrollPane();
        rightPanel.setViewportView(newsGroupDetailsPanel);

        updateButton = new JButton("Update");
        updateButton.addActionListener(this);

        buttonPanel = new JPanel();
        buttonPanel.add(updateButton);

        add(buttonPanel, BorderLayout.NORTH);

        this.splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel);
        add(this.splitPane, BorderLayout.CENTER);
        //TODO set to sort by 'SUBSCRIBED desc' 
    }

    private class newsGroupsTaskListener extends AbstractTaskListener<Void, Void>{
        @Override public void failed(TaskEvent<Throwable> event) {
            Throwable t = event.getValue();
            JOptionPane.showMessageDialog(buttonPanel, "Updating Groups Failed: " + ExceptionUtils.getRootCauseMessage(t));
        }

        @Override public void finished(TaskEvent<Void> event) {
            newsGroupsTable.setEnabled(true);
            updateButton.setEnabled(true);
            setCursor(Cursor.getDefaultCursor());
        }
    }
}

